<template>
  <div id="data-view">
    <dv-full-screen-container :key="fullScreenKey">
      <!--      顶部模块-->
      <TopHeader :nav="navConfig" :name="userInfo.name"></TopHeader>
      <dv-loading v-show="isLoading">Loading...</dv-loading>
      <div v-show="!isLoading" class="main-content">
        <!--        左边表格-->
        <div class="left-content">
          <dv-border-box-10 :color="['#2ACBD8', '#2ACBD8']" :key="box_10_01" style="height: unset">
            <div class="left-top">
              <el-dropdown trigger="click" @command="handleCommand">
                <span class="el-dropdown-link"
                  >{{ `近${selectDropdownItemData}天`
                  }}<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-for="(item, index) in dropdownItemData"
                    :key="index"
                    :command="item"
                    >{{ `近${item}天` }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <div class="left-charts">
              <div class="left-item">
                <TrendChart
                  :id="'trend'"
                  :title="`近${selectDropdownItemData}天走势`"
                  ref="trendChartRef"
                  :data="trendData"
                ></TrendChart>
              </div>
              <div class="left-item">
                <OverloadChart
                  :id="'overload'"
                  :title="`近${selectDropdownItemData}天超重统计`"
                  ref="overloadChartRef"
                  :data="overloadData"
                ></OverloadChart>
              </div>
              <div class="left-item last">
                <Ranking
                  :title="`近${selectDropdownItemData}天总排行`"
                  :table-data="rankingData"
                  @click-row="showSiteDetail"
                ></Ranking>
              </div>
            </div>
          </dv-border-box-10>
        </div>
        <!--        中间-->
        <div class="middle-content">
          <div class="middle-top">
            <!--            计分板-->
            <Scoreboard v-if="!isLoading" :data="countData1"></Scoreboard>
            <Scoreboard v-if="!isLoading" :data="countData2"></Scoreboard>
            <Scoreboard v-if="!isLoading" :data="countData3"></Scoreboard>
            <Scoreboard v-if="!isLoading" :data="countData4"></Scoreboard>
          </div>
          <div class="map">
            <!--            地图-->
            <MapChart
              :id="'map'"
              :data="mapData"
              ref="mapChartRef"
              @click-map="playVideo"
            ></MapChart>
          </div>
          <div class="middle-bottom">
            <RealtimeChart :config-data="realtimeData" @click-row="showRealtime"></RealtimeChart>
          </div>
        </div>
        <!--        右边-->
        <div class="right-content">
          <dv-border-box-10 class="right-top" :color="['#2ACBD8', '#2ACBD8']" :key="box_10_02">
            <OverloadChart
              :id="'roll'"
              :title="'轮轴超重统计'"
              :data="rollData"
              x-type="category"
              ref="rollChartRef"
            ></OverloadChart>
          </dv-border-box-10>
          <dv-border-box-10 class="right-middle" :color="['#2ACBD8', '#2ACBD8']" :key="box_10_03">
            <OverloadRanking
              :table-data="overloadRankingData"
              class="carOverloadRanking"
              @click-row="showCarDetail"
            ></OverloadRanking>
          </dv-border-box-10>
          <dv-border-box-10 class="right-bottom" :color="['#2ACBD8', '#2ACBD8']" :key="box_10_04">
            <div class="catch">
              <div class="catch-title">24小时超重抓拍</div>
              <el-carousel height="25vh" class="catch-car" indicator-position="none">
                <el-carousel-item v-for="(item, index) in photoCatch" :key="index">
                  <el-image style="width: 100%; height: 100%" :src="item" :fit="'fill'">
                    <div slot="error" class="image-slot">
                      <span>上传中...</span>
                    </div>
                  </el-image>
                </el-carousel-item>
              </el-carousel>
            </div>
          </dv-border-box-10>
        </div>
      </div>
    </dv-full-screen-container>
    <!--    视频弹窗-->
    <el-dialog
      class="video-dialog"
      :visible.sync="videoDialog"
      width="40%"
      :modal-append-to-body="false"
      :destroy-on-close="true"
    >
      <span slot="title">站点直播</span>
      <div class="player-box" ref="playerScreen" @click="changeSimpleFullScreen">
        <player-box :url="videoUrl"></player-box>
      </div>
    </el-dialog>
    <!--    /视频弹窗-->
    <!--    站点详情-->
    <el-dialog
      class="video-dialog"
      :visible.sync="siteDetailDialog"
      width="40%"
      :modal-append-to-body="false"
      @closed="siteInfo = {}"
    >
      <span slot="title">站点详情</span>
      <site-detail :site-info="siteInfo"></site-detail>
    </el-dialog>
    <!--    /站点详情-->
    <!--    车辆详情-->
    <el-dialog
      class="video-dialog"
      :visible.sync="carDetailDialog"
      width="40%"
      :modal-append-to-body="false"
      @closed="carInfo = {}"
    >
      <span slot="title">车辆详情</span>
      <car-detail :car-info="carInfo"></car-detail>
    </el-dialog>
    <!--    /车辆详情-->
    <!--    实时数据弹窗-->
    <el-dialog
      class="video-dialog"
      :visible.sync="realtimeDetailDialog"
      width="60%"
      :modal-append-to-body="false"
    >
      <span slot="title">实时数据</span>
      <realtime-detail v-if="realtimeDetailDialog" :realtime-id="realtimeId"></realtime-detail>
    </el-dialog>
    <!--    /实时数据弹窗-->
  </div>
</template>

<script>
import TopHeader from '@/views/bashboard/components/TopHeader'
import Scoreboard from '@/views/bashboard/components/Scoreboard'
import MapChart from '@/views/bashboard/components/MapChart'
import TrendChart from '@/views/bashboard/components/TrendChart'
import OverloadChart from '@/views/bashboard/components/OverloadChart'
import Ranking from '@/views/bashboard/components/Ranking'
import RealtimeChart from '@/views/bashboard/components/RealtimeChart'
import OverloadRanking from '@/views/bashboard/components/OverloadRanking'
import PlayerBox from '@/components/player/PlayerBox'
// import { mapState } from 'vuex'
import {
  getBashboardData,
  getDetailsById,
  getListByCarNumber,
  getRealTimeData
} from '@/service/bashboard/bashboard'
import sessionCache from '@/utils/sessionCache'
import SiteDetail from '@/views/bashboard/components/SiteDetail'
import CarDetail from '@/views/bashboard/components/CarDetail'
import RealtimeDetail from '@/views/bashboard/components/RealtimeDetail'
import { toPercentage } from '@/utils/dataConversion'
import { compact } from 'lodash'

export default {
  name: 'Bashboard',
  components: {
    TopHeader,
    Scoreboard,
    MapChart, // 地图组件
    TrendChart, // 走势图表组件
    OverloadChart, // 超载图表组件
    Ranking,
    RealtimeChart,
    OverloadRanking,
    PlayerBox,
    SiteDetail,
    CarDetail,
    RealtimeDetail
  },
  data() {
    return {
      isLoading: true,
      fullScreenKey: 0,
      box_10_01: 1,
      box_10_02: 2,
      box_10_03: 3,
      box_10_04: 4,
      dropdownItemData: [7, 15, 30],
      selectDropdownItemData: 7,
      // 用户数据
      userInfo: {
        name: '',
        avatarUrl: ''
      },
      // 导航链接
      navConfig: [
        '/bashboard/bashboard',
        '/source_management',
        '/early_warning',
        '/analyse',
        '/user'
      ],
      // 站点总数
      countData1: {
        // title: '站点总数',
        // count: '11'
      },
      // 今日检测总数
      countData2: {
        // title: '今日检测总数',
        // count: '247',
        // pDay: '日环比:73.49%',
        // pWeek: '周环比:34.21%'
      },
      // 今日超限总数
      countData3: {
        // title: '今日超限总数',
        // count: '18'
      },
      // 今日超限率(%)
      countData4: {
        // title: '今日超限率(%)',
        // count: '0.69',
        // pDay: '日环比:-73.49%',
        // pWeek: '周环比:34.21%'
      },
      // 地图数据
      mapData: [],
      // 近30天走势
      trendData: [],
      // 近30天超限统计
      overloadData: [],
      // 近30天总排行
      rankingData: [],
      // 轮轴数超限统计数据
      rollData: [],
      // 车辆超载排行
      overloadRankingData: [],
      // 24小时抓拍
      photoCatch: [],
      // 视频播放弹窗
      videoDialog: false,
      // 视频播放地址
      videoUrl: '',
      // 站点详情弹窗
      siteDetailDialog: false,
      // 站点数据
      siteInfo: {},
      // 车辆详情弹窗
      carDetailDialog: false,
      // 车辆详情数据
      carInfo: {},
      // 实时数据弹窗
      realtimeDetailDialog: false,
      realtimeId: '',
      // 轮询计时器
      timer: null,
      // 实时数据
      realtimeMsg: []
    }
  },
  created() {
    this.getBashboardData(this.selectDropdownItemData)
    // 防止实时数据滚动出错
    setTimeout(() => {
      this.getRealTimeData()
    }, 1000)
    // this.$store.dispatch('m_msg/WEBSOCKET_INIT')
    // console.log('session数据', sessionCache.getItem('tenant'))
    this.userInfo.name = sessionCache.getItem('tenant').username
    this.timer = setInterval(() => {
      // console.log('计时器', this.realtimeMsg)
      this.getBashboardData(this.selectDropdownItemData)
      this.getRealTimeData()
    }, 30000)
  },
  beforeDestroy() {
    clearInterval(this.timer)
    // this.$store.commit('m_msg/WEBSOCKET_CLOSED')
  },
  computed: {
    // ...mapState('m_msg', ['realtimeMsg']),
    // 实时数据
    realtimeData() {
      if (this.realtimeMsg.length > 0) {
        return this.realtimeMsg.map((item) => [
          item.id,
          item.siteName,
          item.carNum,
          item.totalWeight + 'KG',
          item.overweightType > 1 ? '是' : '否',
          item.createTime
        ])
      } else {
        return []
      }
    }
  },
  methods: {
    // 下拉框点击事件
    handleCommand(command) {
      this.selectDropdownItemData = command
      this.getBashboardData(this.selectDropdownItemData)
    },
    // 获取大屏数据
    async getBashboardData(offset = 3) {
      // console.log(offset)
      try {
        const data = await getBashboardData({ offset })
        console.log('大屏数据', data)
        if (data.code === 0) {
          const {
            rankingVos,
            overweightVos,
            trendVos,
            mapVo,
            axleCountVos,
            overweightRankingVos,
            pictureUrls
          } = data.data
          // console.log(rankingVos)
          // console.log(overweightVos)
          // console.log(trendVos)
          // console.log(mapVo)
          // console.log(realTimeVos)
          // console.log(axleCountVos)
          // console.log(overweightRankingVos)
          // console.log('抓拍', pictureUrls)
          this.photoCatch = compact(pictureUrls)
          // this.realtimeMsg = realTimeVos
          // 拼接近30天总排行数据
          this.rankingData = []
          // console.log('排行数据', rankingVos)
          rankingVos.forEach((item) => {
            this.rankingData.push({
              siteId: item.siteId,
              name: item.siteName,
              check: item.totalNum,
              overload: item.overweightNum,
              overweightPercent: toPercentage(item.overweightPercent).handleNum2
            })
          })

          // 拼接近30天超限统计柱状图数据
          this.overloadData = []
          overweightVos.forEach((item) => {
            this.overloadData.push([item.date, item.overweightNum])
          })

          // 拼接近30天走势折线图数据
          const checkArr = []
          const normalArr = []
          const overweight = []
          trendVos.forEach((item) => {
            // 检测数
            checkArr.push([item.date, item.totalNum])
            // 正常数
            normalArr.push([item.date, item.normalNum])
            // 超限数
            overweight.push([item.date, item.overweightNum])
          })
          this.trendData = [checkArr, normalArr, overweight]
          // 发送数据并初始化图表
          // this.$bus.$emit('updateTrendData', this.trendData)
          this.$nextTick(() => {
            this.$refs.trendChartRef.initChart()
          })
          // 拼接计分板数据
          // 站点总数
          this.countData1 = {
            title: '站点总数',
            count: mapVo.siteNum
          }
          // 今日检测总数
          this.countData2 = {
            title: '今日检测总数',
            count: mapVo.todayTotalNum
            // pDay: '日环比:73.49%',
            // pWeek: '周环比:34.21%'
          }
          // 今日超限总数
          this.countData3 = {
            title: '今日超重总数',
            count: mapVo.todayOverweightNum
          }
          // 今日超限率(%)
          this.countData4 = {
            title: '超重百分比(%)',
            count: toPercentage(mapVo.todayOverweightPercent).handleNum2
            // pDay: '日环比:-73.49%',
            // pWeek: '周环比:34.21%'
          }
          console.log(mapVo.todayOverweightPercent)

          // 拼接地图数据
          // console.log(mapVo)
          this.mapData = []
          // console.log('地图数据', mapVo.mapSiteVoList)
          mapVo.mapSiteVoList.forEach((item) => {
            this.mapData.push({
              name: item.siteName,
              // 坐标参数
              value: [item.longitude, item.latitude],
              // 自定义对象
              message: {
                // 检测数量
                checkCount: item.todayTotalNum,
                // 超载数量
                overrun: item.todayOverweightNum,
                // 播放地址
                urls: item.urls
              }
            })
          })

          // 拼接轮轴超限统计折线图数据
          this.rollData = []
          axleCountVos.forEach((item) => {
            this.rollData.push([
              this.getAxleNumName(item.axleNum),
              item.overweightNum,
              item.avgOverweightRate
            ])
          })

          // 拼接车辆超限排行数据
          this.overloadRankingData = []
          overweightRankingVos.forEach((item) => {
            this.overloadRankingData.push({
              id: item.id,
              num: item.carNum,
              count: item.totalWeight,
              standard: item.stdWeight,
              overWeight: item.overWeight,
              overRate: item.overRate
            })
          })
          // console.log(this.overloadRankingData)
          this.$nextTick(() => {
            this.$refs.overloadChartRef.initChart()
            this.$refs.rollChartRef.initChart()
            this.$refs.mapChartRef.initChart()
          })
          this.isLoading = false
        }
      } catch (err) {
        console.warn(err)
        this.$message.error('获取大屏数据失败')
      }
    },
    // 获取超限程度名称
    getOverweightName(type) {
      if (type === 0) {
        return '没有超重'
      } else if (type === 1) {
        return '轻度超重'
      } else if (type === 2) {
        return '较轻超重'
      } else if (type === 3) {
        return '严重超重'
      }
    },
    // 获取轴数名称
    getAxleNumName(axleNum) {
      if (axleNum < 6) {
        return axleNum + '轴'
      } else {
        return axleNum + '轴及以上'
      }
    },
    //
    playVideo(message) {
      this.videoDialog = true
      this.videoUrl = message.urls[0]
    },
    // 切换单独全屏
    changeSimpleFullScreen() {
      const el = this.$refs.playerScreen
      const rfs =
        el.requestFullScreen ||
        el.webkitRequestFullScreen ||
        el.mozRequestFullScreen ||
        el.msRequestFullScreen
      if (typeof rfs !== 'undefined' && rfs) {
        rfs.call(el)
        return
      }
      if (typeof window.ActiveXObject !== 'undefined') {
        const wscript = new window.ActiveXObject('WScript.Shell')
        if (wscript) {
          wscript.SendKeys('{F11}')
        }
      }
    },
    // 展示站点详情
    async showSiteDetail(row) {
      this.siteDetailDialog = true
      const data = await getDetailsById({
        id: row.siteId,
        offset: this.selectDropdownItemData
      })
      console.log(data)
      if (data.code !== 0) return
      this.siteInfo = data.data.entity
      // console.log('站点详情', data)
    },
    // 展示车辆详情
    async showCarDetail(row) {
      this.carDetailDialog = true
      const data = await getListByCarNumber({
        carNumber: row.num,
        offset: this.selectDropdownItemData
      })
      console.log(data)
      if (data.code !== 0) return
      // console.log(row)
      // console.log(data.data.entity)
      this.carInfo = data.data.entity
      this.carInfo.dataId = row.id
      // console.log('车辆详情', data)
    },
    // 展示实时数据详情
    showRealtime(row) {
      this.realtimeDetailDialog = true
      // console.log('realtime', row)
      this.realtimeId = row[0]
    },
    // 获取实时数据
    async getRealTimeData() {
      const data = await getRealTimeData()
      if (data.code !== 0) return
      this.realtimeMsg = data.data
    }
  }
}
</script>

<style lang="less" scoped>
#data-view {
  width: 100%;
  height: 100%;
  background-color: #020420;
  color: #fff;

  ::v-deep table {
    //去除表格边框
    th,
    td {
      border-bottom: none !important;
    }
  }

  .el-table {
    background-color: #111441 !important;
  }

  #dv-full-screen-container {
    //background-image: url('~@/assets/img/bg.png');
    background-size: 100% 100%;
    box-shadow: 0 0 3px blue;
    display: flex;
    flex-direction: column;

    .main-content {
      height: 100%;
      display: flex;
      justify-content: space-between;
      padding: 20px;

      .left-content {
        width: 586px;

        .left-top {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 38px;
          background-color: #071b56;
          box-shadow: 0px 0px 10px rgb(136, 213, 255) inset !important;
        }

        .left-charts {
          padding: 13px;
          display: flex;
          flex-direction: column;

          .left-item {
            height: 273px;
            margin-bottom: 13px;
            background-color: #111441;
            box-shadow: 0 0 12px rgba(34, 229, 255, 0.25) inset;
            overflow: hidden;

            &.last {
              height: 298px;
            }
          }
        }
      }

      .middle-content {
        display: flex;
        justify-content: space-between;
        flex-direction: column;
        align-items: center;
        width: 636px;
        height: 100%;

        .middle-top {
          display: flex;
          justify-content: space-around;
          width: 100%;
          height: 80px;
        }

        .map {
          width: 100%;
          height: 500px;
        }

        .middle-bottom {
          width: 636px;
          height: 326px;
        }
      }

      .right-content {
        width: 586px;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-between;

        .right-top {
          width: 586px;
          height: 271px;
        }

        .right-middle {
          width: 586px;
          height: 297px;
        }

        .right-bottom {
          width: 586px;
          height: 326px;
        }

        .catch {
          padding: 15px;
          font-size: 14px;
          font-weight: 600;
          color: #ffffff;
          overflow: hidden;

          .catch-title {
            margin-bottom: 5px;
          }

          .catch-car {
          }
        }

        // 车辆超载排行
        .carOverloadRanking {
          height: 100%;
          overflow: scroll;
        }

        .carOverloadRanking::-webkit-scrollbar {
          display: none;
        }
      }
    }
  }
}

//下拉框样式
.el-dropdown-link {
  cursor: pointer;
  color: #26ffc9;
}

.el-icon-arrow-down {
  font-size: 12px;
}

.el-dropdown-menu {
  background-color: #020420;
  border: 1px solid #88d5ff;

  .el-dropdown-menu__item {
    color: #26ffc9;
  }

  ::v-deep .popper__arrow {
    &::after {
      border-bottom-color: #26ffc9;
    }
  }
}

.video-dialog {
  //width: 40%;
}

.player-box {
  height: 500px;
}

// 弹出层效果
::v-deep .el-dialog__body {
  background-color: #1e222d;
  //border-bottom: 1px solid #dddddd;
}

::v-deep .el-dialog__header {
  background-color: #1e222d;
}

//.dv-border-box-10 {
//  height: unset;
//}
::v-deep .image-slot {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
